package com.crane.common.framework.spring.advice;


import com.crane.common.core.dto.Response;
import com.crane.common.core.exception.AppException;
import com.crane.common.core.exception.BasicErrorCode;
import com.crane.common.core.exception.BizException;
import com.crane.common.core.exception.SysException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.annotation.Order;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.IllegalFormatException;
import java.util.List;

/**
 * 全局的的异常拦截器（拦截所有的控制器）（带有@RequestMapping注解的方法上都会拦截）
 *
 * @author zhenxing.pi
 */
@ControllerAdvice
@Order(-1)
@ResponseBody
public class GlobalExceptionHandler {

    private static final Logger LOGGER = LoggerFactory.getLogger(GlobalExceptionHandler.class);


    @ExceptionHandler(Exception.class)
    public Response handlerException(Exception e, HttpServletRequest request, HttpServletResponse response) {
        response.setCharacterEncoding("utf-8");
        response.setContentType(MediaType.APPLICATION_JSON_VALUE);
        response.setHeader("Access-control-Allow-Origin", "*");
        response.setHeader("Access-Control-Allow-Methods", "*");
        response.setHeader("Access-Control-Allow-Headers", "*");
        response.setStatus(HttpStatus.OK.value());
        if (e instanceof AppException) {
            LOGGER.error("应用异常" + "_" + e.getMessage(), e);
            return Response.buildFailure(((AppException) e).getErrCode(), e.getMessage());
        } else if (e instanceof BizException) {
            LOGGER.error("业务异常" + "_" + e.getMessage(), e);
            return Response.buildFailure(((BizException) e).getErrCode(), e.getMessage());
        } else if (e instanceof SysException) {
            LOGGER.error("系统异常" + "_" + e.getMessage(), e);
            return Response.buildFailure(((SysException) e).getErrCode(), e.getMessage());
        } else if (e instanceof IllegalFormatException) {
            LOGGER.error("非法格式化异常" + "_" + e.getMessage(), e);
            return Response.buildFailure(BasicErrorCode.SYS_ERROR);
        } else if (e instanceof IllegalArgumentException) {
            LOGGER.warn("IllegalArgumentException:{}", e.getMessage());
            return Response.buildFailure(BasicErrorCode.SYS_ERROR);
        } else if (e instanceof org.springframework.web.bind.MethodArgumentNotValidException) {
            LOGGER.warn("MethodArgumentNotValidException:{}", e.getMessage());
            MethodArgumentNotValidException ee = (MethodArgumentNotValidException) e;
            List<ObjectError> errors = ee.getBindingResult().getAllErrors();
            String tips = "参数不合法";
            if (errors.size() > 0) {
                tips = errors.get(0).getDefaultMessage();
            }
            return Response.buildFailure(BasicErrorCode.SYS_ERROR.getErrCode(), tips);
        } else {
            LOGGER.error("控制层Exception异常捕获:{}", e.getMessage(), e);
            return Response.buildFailure(BasicErrorCode.SYS_ERROR);
        }
    }

}
